package leetcode.d_100_199;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class P151 {
    public static void main(String[] args) {
        P151 test = new P151();
        System.out.println(test.reverseWords("  hello world  ")); // world hello
    }

    public String reverseWords(String s) {
        char[] chars = s.toCharArray();
        List<String> ans = new ArrayList<>();
        int i = chars.length-1;
        int j = chars.length-1;
        while(i >= 0) {
            // 去除后面的空格
            while (i >= 0 && chars[i] == ' ') {
                i--;
            }
            j=i;

            // 添加
            while (i >= 0 &&  chars[i] != ' ') {
                i--;
            }
            ans.add(s.substring(i+1, j+1));

            // 去除前面的空格
            while (i >= 0 &&  chars[i] == ' ') {
                i--;
            }
            j=i;
        }

        String res = "";
        for (int k=0; k<ans.size(); k++) {
            res += ans.get(k);
            if (k != ans.size()-1) {
                res += " ";
            }
        }
        return res;
    }
}
